var express = require("express")
var router = express.Router()
var { Mvs, Prouser,Tiwen, Advise, Goods,Cart} = require("../utils/model")
var { createToken, checkToken } = require("../utils/token")

router.get("/test", (req, res) => {
    res.json({
        code: 200,
        msg: "测试接口 成功"
    })


})


//vue---ajax测试接口
router.post("/login", (req, res) => {
    var body = req.body
    console.log(body)
    res.json({
        code: 200,
        msg: "登录成功",
        body
    })
})


//vue---movie电影列表
router.get("/movie", (req, res) => {
    var limit = req.query.limit * 1 || 0
    Mvs.find({}, { _id: 0 })
        .limit(limit)
        .sort({ _id: -1 })
        .then(result => {
            res.json({
                code: 200,
                msg: "获取数据成功",
                result

            })
        })
})

//获取 crsftoken
router.get("/gettoken", (req, res) => {
    // var token = createToken('xmj')
    res.json({
        token: "token",
        msg: "获取token成功",
        type: 1,
        code: 200
    })
})

//myapp登录接口
router.post("/signin", (req, res) => {
    var body = req.body
    console.log(body);
    Prouser.findOne({
        mobile: body.mobile,
    }).then(result => {
        if (result) {
            if (result.password == body.password) {
                var token = createToken({
                    mobile: body.mobile,
                    password: body.password,
                    roleid: result.roleid,  //多存一个roleid在添加用户的时候用
                })
                res.json({
                    code: 200,
                    type: 1,
                    msg: "登录成功",
                    token
                })
            } else {
                res.json({
                    code: 200,
                    type: 0,
                    msg: "登录失败,用户名和密码不匹配"
                })
            }
        } else {
            res.json({
                code: 200,
                type: 0,
                msg: "登录失败,用户名和密码不匹配"
            })
        }
    })
})

//register
router.post("/register", (req, res) => {
          var body = req.body
           //添加用户  1.先判断用户是否存在
            Prouser.findOne({
                mobile: body.mobile,
                username:body.username
            }).then(data => {
                if (data) {
                    res.json({
                        code: 403,
                        type: 0,
                        msg: "手机号码已经存在，请确认数据"

                    })

                } else {
                    body.time = new Date()
                    Prouser.insertMany(body)
                        .then(result => {
                            res.json({
                                code: 200,
                                type: 1,
                                result,
                                msg: "用户添加成功"

                            })
                        })

                }
            })
        })

//获取个人信息  token
router.post("/getuserinfo", (req, res) => {
    checkToken(req, res, ({ mobile }) => {
        Prouser.findOne({
            mobile: mobile
        }).then(result => {
            res.json({
                code: 200,
                msg: "获取信息成功",
                result: result,
                type: 1
            })
        })
    })
})


//添加用户  注册接口  管理员限制 ： 只有管理员跟超级管理员添加用户，管理员不能修改超级管理员
router.post("/adduser", (req, res) => {
    checkToken(req, res, ({ mobile, roleid }) => {
        var body = req.body
        var addroleid = body.roleid
        if (addroleid > roleid) {
            res.json({
                code: 403,
                type: 0,
                msg: "你权限不够，不能添加用户信息"

            })
        } else {
            //添加用户  1.先判断用户是否存在
            Prouser.findOne({
                mobile: body.mobile,
            }).then(data => {
                if (data) {
                    res.json({
                        code: 403,
                        type: 0,
                        msg: "手机号码已经存在，请确认数据"

                    })

                } else {
                    body.time = new Date()
                    Prouser.insertMany(body)
                        .then(result => {
                            res.json({
                                code: 200,
                                type: 1,
                                result,
                                msg: "用户添加成功"

                            })
                        })

                }
            })

        }

    })
})

//查询用户

router.post("/getuserlist", (req, res) => {
    checkToken(req, res, ({ mobile, roleid })=> {
        Prouser.find({},{})
            .sort({ _id: -1 })
            .then(result => {
                console.log(result)
                res.json({
                    code: 200,
                    msg: "获取用户列表成功",
                    result,
                    type: 1

                })
            })
                    .catch(err => {
                        res.json({
                            code: 500,
                            msg: "服务器异常",
                            err,
                            type: 0
                        })
                    })
            })
    })

    //根据_id删除用户
    router.post("/deluser",(req,res)=>{
        checkToken(req,res,({mobile,roleid})=>{
            Prouser.remove({
                _id:req.body._id
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: "用户删除成功",
                    result,
                    type: 1

                })
            })
                    .catch(err => {
                        res.json({
                            code: 500,
                            msg: "服务器异常",
                            err,
                            type: 0
                        })
                    })
            })

        })

        //根据_id 修改用户信息
    router.post("/updateuserone",(req,res)=>{
        checkToken(req,res,({mobile,roleid})=>{
           var body ={...req.body,time:new Date()}
        //    delete body[_id]
            Prouser.updateMany({
                _id:req.body._id
            },{
                $set:body
            })
            .then(result => {
                res.json({
                    code: 200,
                    msg: "用户修改成功",
                    result,
                    type: 1

                })
            })
                    .catch(err => {
                        res.json({
                            code: 500,
                            msg: "服务器异常",
                            err,
                            type: 0
                        })
                    })
            })

        })

//提交体温记录
router.post("/addtiwen",(req,res)=>{
    const {
        tiwen
    } = req.body

    checkToken(req,res,({mobile,roleid})=>{
        Prouser.findOne({
            mobile
        }).then(userinfo=>{
            Tiwen.insertMany({
                time:new Date(),
                mobile,
                username:userinfo.username,
                tiwen,
                ishei:"0",
                is_yin:"1"
            }).then(data=>{
                Tiwen.find({mobile},{})
                .sort({_id:-1})
                .then(result=>{
                    res.json({
                        code:200,
                        msg:"添加成功",
                        result,
                        type:1
                    })
                })
               .catch(err=>{
                res.json({
                    code:500,
                    msg:"服务器异常",
                    err,
                    type:0
                })
               
              })
                
          })
        
        })
    
    })
})

//获取我的体温记录

router.post("/mytiwenlist",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        Tiwen.find({
            mobile
        },{})
        .sort({_id:-1})
        .then(result=>{
            res.json({
                code:200,
                msg:"查询成功",
                result,
                type:1
            })
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

//根据_id 删除体温记录
router.post("/delOnelist",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        Tiwen.remove({
            _id:req.body._id
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"删除成功",
                result,
                type:1
            })
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

//根据_id 修改体温记录
router.post("/updatetiwenone",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        var body = {...req.body,time:new Date()}
        Tiwen.updateMany({
            _id:req.body._id
        },{
            $set:body
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"修改成功",
                result,
                type:1
            })
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器成功",
                err,
                type:0
            })
        })
    })
})

//根据 _id 修改是否检测
router.post("/updateishei",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        Tiwen.updateMany({
            _id:req.body._id
        },{
            $set:{
                ishei:req.body.ishei
            }
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"修改成功",
                result,
                type:1
            })
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })

        })
    })
})

//根据_id 修改核算结果
router.post("/updateisyin",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        Tiwen.updateMany({
            _id:req.body._id
        },{
            $set:{
                is_yin:req.body.is_yin
            }
        })
        .then(res=>{
            res.json({
                code:200,
                msg:"修改成功",
                result,
                type:1
            })
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

// 获取首页的 banner
router.post("/gethomebanner",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        res.json({
            msg:"获取数据成功",
            code:200,
            type:1,
            result:[
                {
                    imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599974737816&di=374d889e4862a64f82cd95710092aa8a&imgtype=0&src=http%3A%2F%2Fimg.taopic.com%2Fuploads%2Fallimg%2F130307%2F267859-13030FU61687.jpg",
                    
                },
                {
                    imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599974737813&di=be525ec178329d5485acb3565178cf40&imgtype=0&src=http%3A%2F%2Fpic171.nipic.com%2Ffile%2F20180628%2F24701680_151532401000_2.jpg",
                    text:"文化社区，知识传承"
                },
                {
                    imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599975202527&di=1ab50c3eda3f00771842e826b28dccf1&imgtype=0&src=http%3A%2F%2Fimage.bitauto.com%2Fdealer%2Fnews%2F100132592%2F3444a267-5a86-4e2e-adeb-30e38a2e8476.jpg",
                    text:"宝贝的彩色世界"
                },
                {
                    imgUrl:"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1599752385889&di=04bd13128904db109a607a7f11650d50&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20200311%2F62a61f7498c94bf5935fc371b58f021b.jpeg",
                    text:"注意卫生，让我们一起战胜新型冠状病毒"
                }
            ]
        })
    })
}) 

//提交意见 add
router.post("/addadvise",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        console.log(req.body)
        Prouser.findOne({
            mobile
        }).then(userinfo=>{
            Advise.insertMany({
                time:new Date(),
                mobile,
                username:userinfo.username,
                reply:[],
                ...req.body
            }).then(result=>{
                res.json({
                    code:200,
                    msg:"添加成功",
                    result,
                    type:1
                })
            }).catch(err=>{
                res.json({
                    code:500,
                    msg:"服务器异常",
                    err,
                    type:0
                })
            })

        })
    })
})

// 获取意见列表  
router.post("/getadviselist",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var obj = {}
        Advise.find(obj,{})
        .sort({_id:-1})
        .then(result=>{
            res.json({
                code:200,
                msg:"意见查询成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

// 根据_id 删除意见列表 
router.post("/delAdviseOne",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        Advise.remove({
            _id:req.body._id
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"意见删除成功",
                result,
                type:1
            })
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
}) 


// 获取意见 
router.post("/getadvisebyid",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var obj = {
            _id:req.body._id
        }
        Advise.findOne(obj,{})
        .then(result=>{
            res.json({
                code:200,
                msg:"查询成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

// 修改意见 
router.post("/updateadvisebyid",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var obj = {
            _id:req.body._id
        }
        Advise.updateMany(obj,{
            $set:{
                time:new Date(),
                title:req.body.title,
                content:req.body.content,
                category:req.body.category
            }
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"修改成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})


// 提交意见回复


router.post("/addreply",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var {_id,username,tips} = req.body;
        Advise.findOne({
            _id
        }).then(data=>{
            var reply = data.reply || [];
            console.log(reply);
            reply.push({
                author:username,
                mobile,
                roleid,
                tips,
                time:new Date(),
                id:reply.length
            })

            Advise.updateMany({
                _id,
            },{
                $set:{
                    reply
                }
            }).then(result=>{
                res.json({
                    code:200,
                    msg:"回复成功",
                    result,
                    type:1
                })    
            }).catch(err=>{
                res.json({
                    code:500,
                    msg:"服务器异常",
                    err,
                    type:0
                })
            })
        })
    })
})

// 商品列表 
router.post("/goodlist",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var obj = {}
        var limit = req.body.limit || 0;
        Goods.find(obj,{})
        .limit(limit)
        .sort({_id:-1})
        .then(result=>{
            res.json({
                code:200,
                msg:"商品查询成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})


// 商品分类去重
router.post("/goodtypelist",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        Goods.distinct("type")
        .then(result=>{
            res.json({
                code:200,
                msg:"商品分类查询成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

//获取商品详情
router.post("/getgoodone",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        Goods.findOne({
            _id:req.body._id
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"商品查询成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

// 添加商品到我的购物车
router.post("/addtocart",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        const {
            goodId,
            count
        } = req.body;
        var body = req.body;
        console.log(mobile)
        Cart.findOne({
            goodId,
        })
        .then(data=>{
            if(data){
                // count 累加 ++ 
                Cart.updateMany({
                    goodId
                },{
                    $set:{
                        time:new Date()
                    },
                    $inc:{
                        count:count *1 
                    }
                }).then(result=>{
                    res.json({
                        code:200,
                        msg:"添加商品成功",
                        result,
                        type:1
                    }) 
                }) 
            }else{
                // 直接新增 
                body.time = new Date();
                body.checked = false;
                body.mobile = mobile;
                console.log(body);
                Cart.insertMany(body)
                .then(result=>{
                    res.json({
                        code:200,
                        msg:"新增商品成功",
                        result,
                        type:1
                    }) 
                }) 
            }
        })
        .catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})


// 根据 mobile 获取我的购物车信息 
router.post("/getmycart",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        Cart.find({
            mobile
        })
        .sort({
            _id:-1
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"查询成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

// 修改数量

router.post("/changecartcount",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var {_id,count} = req.body;
        Cart.updateMany({
            _id
        },{
            $set:{
                count:count*1
            }
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"数量更新成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})


// 修改选中 
router.post("/changecartcheck",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        var {_id,checked} = req.body;
        var obj = {}
        if(_id){
            obj = {_id}
        }
        Cart.updateMany(obj,{
            $set:{
                checked:checked
            }
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"更新成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})


// 删除
router.post("/delcartone",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        Cart.remove({
            _id:req.body._id
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"删除成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})

// 批量删除  判断选中 
router.post("/delcartcheck",(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{ 
        Cart.remove({
            mobile,
            checked:true
        })
        .then(result=>{
            res.json({
                code:200,
                msg:"批量删除成功",
                result,
                type:1
            })    
        }).catch(err=>{
            res.json({
                code:500,
                msg:"服务器异常",
                err,
                type:0
            })
        })
    })
})



// 上传头像  
// multer 
var multer = require("multer");
var storage = multer.diskStorage({
    destination: function (req, file, cb) {   // 头像存放的目录 
        cb(null, './public/avatar') //. 文件路径
    },
    filename: function (req, file, cb) {  // 新的文件名 
        cb(null, Date.now()+"WH2004"+file.originalname);  //  originalname 原文件名 
    }
})

var upload  =  multer({ storage: storage }).any();  // 可以上传任何格式的图片

router.post("/uploadpic",upload,(req,res)=>{
    checkToken(req,res,({mobile,roleid})=>{
        if(req.files){
            console.log(req.files); 
            var avatar = req.files[0].path;  // 头像的服务器地址 
             Prouser.updateMany({
                 mobile
             },{
                 $set:{
                     avatar
                 }
             }).then(result=>{
               res.json({
                    code:200,
                    msg:"头像上传成功",
                    type:1,
                    avatar
                })


             }).catch(err=>{
                res.json({
                    code:500,
                    msg:"服务器异常",
                    type:0,
                   
                })
                 
             })
        }else{
            res.json({
                code:200,
                msg:"头像上传失败",
                type:0,
                
            })

        }
       
        
    })
})




module.exports = router;